package com._54programer.demo.ws;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * @author SN
 * @date Created by on 2019/11/29
 * @description Ws服务端
 */
public class WsServer {

    private int port;

    public WsServer(int port) {
        this.port = port;
    }

    public void run() throws Exception{
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();

                            //http编解码器, 用于支持http协议, 因为websocket协议基于http协议
                            pipeline.addLast(new HttpServerCodec());
                            //以块的方式写, 添加ChunkedWriteHandler处理器
                            pipeline.addLast(new ChunkedWriteHandler());
                            //http的数据是分段传输, HttpObjectAggregator可以将多个段聚合
                            pipeline.addLast(new HttpObjectAggregator(8912));

                            /**
                             * 心跳检测
                             * IdleStateHandler: 空闲检测
                             * 参数: 读空闲、写空闲、读写空闲
                             * 针对客户端，如果在1分钟时没有向服务端发送读写心跳(ALL)，则主动断开
                             * 如果是读空闲或者写空闲，不处理
                             */
                            pipeline.addLast(new IdleStateHandler(20, 30, 60));
                            //自定义的空闲状态检测
                            pipeline.addLast(new HeartBeatHandler());

                            /**
                             * WebSocketServerProtocolHandler的功能是将http协议升级为ws协议, 保持长连接
                             * /ws：服务器处理的协议，指定给客户端连接访问的路由
                             * 该handler会帮你处理握手动作
                             * websocket是以frames进行数据传输, 不同的数据类型对应不同的frames
                             */
                            pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));

                            //自定义Handler
                            pipeline.addLast(new WsServerHandler());
                        }
                    });
            ChannelFuture channelFuture = bootstrap.bind(port).sync();
            channelFuture.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        WsServer groupChatServer = new WsServer(10000);
        groupChatServer.run();
    }
}
